﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.Web.Hosting;

using SBPweb.PROvibe.Server.Library.Hosting;
using SBPweb.PROvibe.Server.Library.Services;

using SBPweb.PROvibe.Server.Modules.ServiceProvider.Contracts;

using SBPweb.PROvibe.Shared.Library.Components;

namespace SBPweb.PROvibe.Server.Modules.ServiceProvider
{

    public class ServiceProviderService : ServiceBase<IServiceProviderService>, IServiceProviderService
    {

        #region Fields

        private CustomServiceVirtualPathProvider pathProvider = new CustomServiceVirtualPathProvider();

        #endregion

        #region Constructor logic

        public ServiceProviderService(IModule parentModule)
            : base(parentModule)
        {
            VirtualPathMappings = new ReadOnlyCollection<string>(CustomServiceHostFactory.ServiceHosts.Keys.ToList());
            HostingEnvironment.RegisterVirtualPathProvider(pathProvider);
        }

        #endregion

        #region Properties
        
        public override string Name
        {
            get
            {
                return "ServiceProviderService";
            }
        }

        public ReadOnlyCollection<string> VirtualPathMappings
        {
            get;
            private set;
        }

        #endregion

        #region Methods

        protected override void OnInitialize()
        {
            //IDataProviderService isps = this.Parent.PublicServices.Get<IDataProviderService>();
        }

        protected override void OnTerminate()
        {
        }
        
        public ServiceHost CreateServiceHost<TService, TContract>(IModule parentModule, string virtualPathOfService)
            where TService : RIA.Shared.Contracts.Services.IService
            where TContract : RIA.Shared.Contracts.Services.IService
        {
            string moduleName = parentModule.Name;
            if (!virtualPathOfService.StartsWith(moduleName))
            {
                virtualPathOfService = string.Format("{0}/{1}", moduleName, virtualPathOfService);
            }
            string rootNamespace = string.Format("{0}{1}/", Library.Constants.Services.DefaultNamespace, moduleName);
            CustomServiceHost<TService, TContract> host = new CustomServiceHost<TService, TContract>(rootNamespace, CustomServiceVirtualPathProvider.VirtualWcfDirectoryName + "/" + virtualPathOfService);
            CustomServiceHostFactory.ServiceHosts.TryAdd(virtualPathOfService, host);
            return host;
        }

        #endregion

    }

}